package com.qd.p2p.web.action.user;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import com.qdlc.p2p.biz.service.user.UserRegistService;
import com.qdlc.p2p.biz.util.UserReturnResult;
import com.qdlc.p2p.common.core.ReturnResult;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;

import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.service.AdditionalUserDrawLotteryService;
import com.qdlc.p2p.biz.service.CooperationLoginService;
import com.qdlc.p2p.biz.service.NewActivityPlanService;
import com.qdlc.p2p.biz.service.NewActivityRuleService;
import com.qdlc.p2p.biz.service.NoticeService;
import com.qdlc.p2p.biz.service.UpRateService;
import com.qdlc.p2p.biz.service.UserCacheService;
import com.qdlc.p2p.biz.service.UserIdentifyService;
import com.qdlc.p2p.biz.service.UserLoginRecordService;
import com.qdlc.p2p.biz.service.UserService;
import com.qdlc.p2p.biz.service.UserSignService;
import com.qdlc.p2p.biz.service.user.UserMobilePhoneService;
import com.qdlc.p2p.biz.util.NoticeTemplateSender;
import com.qdlc.p2p.biz.util.mail.Mail;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.constant.NoticeTplNid;
import com.qdlc.p2p.common.constant.UserNature;
import com.qdlc.p2p.common.constant.UserType;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.exception.UserException;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.MessageCheck;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.checkrule.SafetyRuleCheck;
import com.qdlc.p2p.dal.common.RuleCheckHelper;
import com.qdlc.p2p.dal.dao.AdditionalDrawLotteryRuleDao;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserCache;
import com.qdlc.p2p.dal.model.UserModel;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * 用户账户
 *
 * @author yy
 * @version 1.0
 * @since
 */
public class UserAction extends BaseAction<User> implements ModelDriven<User> {

    @Resource
    private UserService userService;

    @Resource
    private NewActivityPlanService newActivityPlanService;

    @Resource
    private UserCacheService userCacheService;

    @Resource
    private UserIdentifyService userIdentifyService;

    @Resource
    private CooperationLoginService cooperationLoginService;

    @Resource
    private UpRateService upRateService;

    @Resource
    private NoticeService noticeService;

    @Resource
    private AdditionalUserDrawLotteryService additionalUserDrawLotteryService;

    @Resource
    private UserLoginRecordService userLoginRecordService;

    @Resource
    private NewActivityRuleService newActivityRuleService;

    @Resource
    private UserSignService userSignService;

    @Resource
    private AdditionalDrawLotteryRuleDao additionalDrawLotteryRuleDao;
    
    @Resource
    UserMobilePhoneService userMobilePhoneService;

    @Resource
    UserRegistService userRegistService;
    
    /**
     * 平台安全性规则 *
     */
    private SafetyRuleCheck safetyRuleCheck = RuleCheckHelper.getValue(SafetyRuleCheck.class);

    private Map<String, Object> data;

    private MessageCheck messageCheck=new MessageCheck();
    
    /**
     * 判断用户名是否已存在
     */
    @Action(value = "/user/checkUsername", interceptorRefs = {@InterceptorRef("ajaxSafe"), @InterceptorRef("globalStack")})
    public void checkUsername() throws Exception {
    	// 安全规则-禁止使用敏感用户名
    	try {
            safetyRuleCheck.hasFontUnallowedUsername(model);
        } catch (Exception e) {
            printWebJson(getStringOfJpaObj(false));
            return;
        }
    	
    	//检测用户名是否已经存在
        boolean existUserName = UserUtils.exsitUserNameOrPhomeOrEmail(model.getUserName());
        boolean result = !existUserName;
        printWebJson(getStringOfJpaObj(result));
    }

    /**
     * 判断邮箱是否已被使用
     *
     * @return
     * @throws Exception
     */
    @Action(value = "/user/checkEmail", interceptorRefs = {@InterceptorRef("ajaxSafe"), @InterceptorRef("globalStack")})
    public void checkEmail() throws Exception {
        boolean result = UserUtils.exsitUserNameOrPhomeOrEmail(model.getEmail());
        printWebJson(getStringOfJpaObj(!result));
    }

    /**
     * 判断身份证号码是否已被使用
     * @return
     * @throws Exception
     */
    @Action(value = "/user/checkCardId", interceptorRefs = {@InterceptorRef("ajaxSafe"), @InterceptorRef("globalStack")})
    public void checkCardId() throws Exception {
        int count = userService.countByCardId(model.getCardId());
        boolean result = count <= 0;
        printWebJson(getStringOfJpaObj(result));
    }

    /**
     * 判断手机号码是否已被使用
     * @return
     * @throws Exception
     */
    @Action(value = "/user/checkMobilePhone", interceptorRefs = {@InterceptorRef("ajaxSafe"), @InterceptorRef("globalStack")})
    public void checkMobilePhone() throws Exception {
        boolean result = true;
        if (StringUtil.isBlank(model.getMobilePhone())) {
            result = false;
        }
        
        //检测手机号码是否已经存在
        if(result){
        	boolean existMobilePhone = UserUtils.exsitUserNameOrPhomeOrEmail(model.getMobilePhone());
        	result = !existMobilePhone;
        }
        
        printWebJson(getStringOfJpaObj(result));
    }

    /**
     * 第二部进行邮箱认证
     *
     * @return
     * @throws Exception
     */
    @Action("/user/doRegisterStep1")
    public String doRegisterStep1() throws Exception {
        model = userService.activationEmail(paramString("id"));
        request.setAttribute("msg", "邮箱激活成功，注册成功！");
        request.setAttribute("pwd", model.getPwd());
        request.setAttribute("uId", model.getUserId());
        return "regresult";
    }

    /**
     * 初始化密码页面
     *
     * @return
     * @throws Exception
     */
    @Action("/user/initLoginPwd")
    public String initLoginPwd() throws Exception {
        User user = userService.find(model.getUserId());
        String referer = request.getHeader("Referer");
        if (referer == null) {
            throw new UserException("为了确保信息安全，请通过发送给您的邮箱点击访问");
        }
        if (user.getPwd() != null && !"".equals(user.getPwd())) {
            throw new UserException("已经初始化过密码");
        }
        UserCache userCache = UserUtils.getUserCacheByUserId(user.getUserId());
        request.setAttribute("companyName", userCache.getCompanyName());
        request.setAttribute("uId", model.getUserId());
        return "initLoginPwd";
    }

    /**
     * 初始化密码
     *
     * @return
     * @throws Exception
     */
    @Action("/user/initPwd")
    public void initPwd() throws Exception {
        if (!model.getPwd().equals(paramString("confirmPassword"))) {
            throw new UserException("两次输入的密码不一致！");
        }
        User user = userService.find(model.getUserId());
        if (user.getPwd() != null && !"".equals(user.getPwd())) {
            throw new UserException("您已经初始化过密码！");
        }
        user.setPwd(model.getPwd());
        userService.modifyPwd(user);
        printWebSuccess();
    }

    /**
     * 邮箱激活 重新发送激活邮件
     *
     * @return
     * @throws Exception
     */
    @Action("/user/sentActivationEmail")
    public String sentActivationEmail() throws Exception {
        if (model == null || model.getUserId() == 0) {
            throw new UserException("用户不存在，激活邮件发送失败！", 1);
        }
        model = userService.find(model.getUserId());

        Global.setTransfer("user", model);
        Global.setTransfer("activeUrl", "/user/doRegisterStep1.html?id=" + Mail.getInstance().getdecodeIdStr(model));
        NoticeTemplateSender.newInstance(model, NoticeTplNid.NOTICE_EMAIL_ACTIVE).send();

        printWebSuccess();
        return null;
    }

    @Action("/user/partner/doRegister")
    public void doPartnerRegister() throws Exception {
        data = new HashMap<String, Object>();

        ReturnResult result = null;
        UserModel userModel = new UserModel();
        
        // PS 非合作者不能注册
        String partner = paramString("partner");
        String userName = paramString("userName");
        String passWord = paramString("passWord");
        String mobilePhone = paramString("mobilePhone");

        userModel.setUserName(userName);
        userModel.setPwd(passWord);
        userModel.setMobilePhone(mobilePhone);

        if(!"11E72348965EB72C92A549DD5A33911231".equals(partner)){
            throw new UserException("非合作者不能注册！", BusinessException.TYPE_JSON);
        }
        try {
            result = userRegistService.doRegister(userModel, true);
        } catch (Exception e) {
            printWebResult(e.getMessage(),false);
        }

        if(result instanceof UserReturnResult){
            printWebResult("注册成功",true);
        }else{
            printWebResult(result.getErrorInfo(),false);
        }
    }

    private void checkRegister(UserModel model) {
        if (StringUtil.isEmpty(model.getUserName())) {
            throw new UserException("用户名不能为空!！", BusinessException.TYPE_JSON);
        } else if (StringUtil.isEmpty(model.getPwd())) {
            throw new UserException("密码不能为空!！", BusinessException.TYPE_JSON);
        } else if (StringUtil.isEmpty(model.getMobilePhone())) {
            throw new UserException("手机号码不能为空!！", BusinessException.TYPE_JSON);
        } else if (model.getUserType() != 1 && model.getUserType() != 2 && model.getUserType() != 3) {
            throw new UserException("该用户类型不存在!！", BusinessException.TYPE_JSON);
        } else if (model.getAddTime() == null) {
            throw new UserException("时间不能为空!！", BusinessException.TYPE_JSON);
        }

        // TODO 安全规则-禁止使用敏感用户名
        safetyRuleCheck.hasFontUnallowedUsername(model);
        int count = userService.countByUserName(model.getUserName());
        if(count > 0){
            throw new UserException("用户名已经存在!！", BusinessException.TYPE_JSON);
        }

        count = userService.countByMobilePhone(model.getMobilePhone());
        if (count > 0) {
            throw new UserException("手机号已经存在!！", BusinessException.TYPE_JSON);
        }
    }

    /**
     * 获取距离上次短信发送剩余时间
     * @return
     * @throws Exception
     */
    @Action("/user/messageTimeCheck")
    public void messageTimeCheck() throws Exception{
        String mobile=paramString("mobile");
        User user=getSessionUser();
        if(user!=null){
            mobile=user.getMobilePhone();
        }
        data = new HashMap<String, Object>();
        data.put("remain",messageCheck.mobileCheck(mobile));
        printWebJson(getStringOfJpaObj(data));
    }
}
